package com.ruisitech.bi.config;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import com.alibaba.cloud.nacos.registry.NacosRegistration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.util.Set;

/**
 * 系统初始化操作
 */
@Configuration
@Slf4j
public class WebAppConfig {

    @Autowired
    private NacosRegistration registration;

    @Autowired
    private NacosAutoServiceRegistration nacosAutoServiceRegistration;
    //获取运行时的环境，dev为本地开发环境
//    @Value("${spring.profiles.active}")
//    private String env;


    /**
     * 将服务注册到nacos
     */
    @PostConstruct
    public void nacosServerRegister() {
//        if (registration != null && StringUtils.isNotEmpty(env) && !env.equals("dev")) {
        if (registration != null) {
            try {
                Integer tomcatPort = new Integer(getTomcatPort());
                //设置端口号
                registration.setPort(tomcatPort);
                //将服务注册到nacos
                nacosAutoServiceRegistration.start();
            } catch (Exception e) {
                log.error("获取外部Tomcat端口异常：{}", e);
            }
        }
    }

    /**
     * 获取外部tomcat端口
     *
     * @return
     */
    public static String getTomcatPort() throws Exception {
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        String port = objectNames.iterator().next().getKeyProperty("port");
        return port;
    }

}